﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Jzy.Model.Mail;
using Frame.Lib.Core.Base;
using Frame.Lib.Utilities;


namespace Jzy.DAL.Mail
{
    public class WebMailDAL:BaseDAL
    {
        private int _userID;
        public WebMailDAL(int userID)
        {
            _userID = userID;
        }

        public DataTable GetList(int folderID, MailStatus status,string accountAddr)
        {
            string sql = "select ID, Status, HasAttachment,FromName,ToAddr, Name, InputTime  from " + OTableName.WebMail + " where UserID = " + _userID + " and  FolderID = " + folderID + " and AccountAddr='" + accountAddr + "'";
            if (status != MailStatus.All)
            {
                if (status == MailStatus.UnRead)
                {
                    sql += " and Status = 0";
                }
                else
                {
                    sql += " and Status & " + (int)status + " = " + (int)status;
                }
            }
            sql += " order by InputTime desc";

            DataTable dt = dbOper.Query(sql);
            return dt;
        }

        public void Move(List<int> lstMailIDs, object destFolder)
        {
            string mailIDs = ConvertUtil.ConvertToDbStr(lstMailIDs);
            string sql = "update " + OTableName.WebMail + " set FolderID = " + destFolder + " where ID in (" + mailIDs + ")";
            dbOper.RunSql(sql);
        }

        public void SaveToDraft(int mailID)
        {
            string sql = "update " + OTableName.WebMail + " set FolderID = " + (int)MailSysFolder.草稿箱 + " where ID = " + mailID;
            dbOper.RunSql(sql);
        }

        //public byte GetStatus(int 

        public void Clear(object folderID)
        {
            string sql = "delete from " + OTableName.WebMail + " where UserID = " + _userID + " and FolderID = " + folderID;
            dbOper.RunSql(sql);
        }

        public int GetUnreadMailCount()
        {
            string sql = "select count(*) from " + OTableName.WebMail + " where UserID = " + _userID + " and FolderID = " + (int)MailSysFolder.收件箱 + " and Status | " + (int)MailStatus.UnRead + " = " + (int)MailStatus.UnRead;
            int count = dbOper.GetScalar<int>(sql);
            return count;
        }

        public List<string> GetMailGuid()
        {
            string sql = "select MailGuid from " + OTableName.WebMail + " where UserID = @p0";
            IEnumerable<string> ids = dbOper.Query<string>(sql, _userID);
            return ids.ToList();
        }

        public void SetStatus(int MailID, MailStatus status)
        {
            string sql = "update " + OTableName.WebMail + " set Status = Status | " + (int)status + " where ID = " + MailID;
            dbOper.RunSql(sql);
        }
    }
}
